// 监听来自popup的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  try {
    console.log('📨 收到消息:', request);
    
    if (request.action === 'scrapePrompts') {
      console.log('🕷️ 开始执行爬取任务...');
      scrapePrompts().then(result => {
        console.log('✅ 爬取任务完成:', result);
        sendResponse(result);
      }).catch(error => {
        console.error('❌ 爬取任务失败:', error);
        sendResponse({success: false, error: error.message});
      });
      return true; // 保持消息通道开放
    } else if (request.action === 'showMenu') {
      console.log('📋 显示悬浮菜单...');
      showFloatingMenu();
      sendResponse({success: true});
    } else if (request.action === 'hideMenu') {
      console.log('❌ 隐藏悬浮菜单...');
      hideFloatingMenu();
      sendResponse({success: true});
    }
  } catch (error) {
    console.error('❌ 消息处理错误:', error);
    sendResponse({success: false, error: error.message});
  }
});

// 显示悬浮菜单
function showFloatingMenu() {
  console.log('🎨 开始创建悬浮菜单...');
  
  // 移除所有页面中已存在的菜单
  const existingMenus = document.querySelectorAll('#prompt-manager-floating-menu');
  existingMenus.forEach(menu => {
    console.log('🗑️ 移除已存在的菜单');
    menu.remove();
  });
  
  // 移除所有页面中已存在的样式
  const existingStyles = document.querySelectorAll('#prompt-manager-floating-menu-style');
  existingStyles.forEach(style => {
    style.remove();
  });

  // 创建悬浮菜单
  const menu = document.createElement('div');
  menu.id = 'prompt-manager-floating-menu';
  menu.style.cssText = `
    position: fixed !important;
    top: 20px !important;
    right: 20px !important;
    z-index: 2147483647 !important;
    font-family: Arial, sans-serif !important;
    pointer-events: auto !important;
  `;
  
  menu.innerHTML = `
    <div class="floating-menu">
      <div class="menu-header">
        <div class="menu-title">Prompt Manager</div>
        <div class="menu-controls">
          <button class="control-button minimize-button" title="缩小">−</button>
          <button class="control-button close-button" title="关闭">×</button>
        </div>
        <button class="expand-button" style="display: none;" title="展开">+</button>
      </div>
      <div class="menu-container">
        <button class="menu-button manage">
          <span>📝</span> 提示词管理
        </button>
        <button class="menu-button scrape">
          <span>🕷️</span> 爬取提示词
        </button>
        <button class="menu-button export">
          <span>📊</span> 导出Excel
        </button>
      </div>
    </div>
  `;

  // 添加样式
  const style = document.createElement('style');
  style.id = 'prompt-manager-floating-menu-style';
  style.textContent = `
    .floating-menu {
      background: white !important;
      border-radius: 12px !important;
      box-shadow: 0 8px 32px rgba(0,0,0,0.15) !important;
      border: 1px solid #e0e0e0 !important;
      transition: all 0.3s ease !important;
      overflow: hidden !important;
      min-width: 280px !important;
      max-width: 320px !important;
    }
    
    .menu-header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
      color: white !important;
      padding: 12px 16px !important;
      display: flex !important;
      justify-content: space-between !important;
      align-items: center !important;
    }
    
    .menu-title {
      font-size: 14px !important;
      font-weight: 600 !important;
    }
    
    .menu-controls {
      display: flex !important;
      gap: 8px !important;
    }
    
    .control-button {
      background: rgba(255,255,255,0.2) !important;
      border: none !important;
      color: white !important;
      width: 24px !important;
      height: 24px !important;
      border-radius: 4px !important;
      cursor: pointer !important;
      display: flex !important;
      align-items: center !important;
      justify-content: center !important;
      font-size: 12px !important;
      transition: background-color 0.2s !important;
    }
    
    .control-button:hover {
      background: rgba(255,255,255,0.3) !important;
    }
    
    .menu-container {
      padding: 16px !important;
      display: flex !important;
      flex-direction: column !important;
      gap: 12px !important;
    }
    
    .menu-button {
      padding: 12px 16px !important;
      border: none !important;
      border-radius: 8px !important;
      color: white !important;
      cursor: pointer !important;
      font-size: 14px !important;
      font-weight: 500 !important;
      transition: all 0.2s !important;
      display: flex !important;
      align-items: center !important;
      gap: 8px !important;
    }
    
    .menu-button:hover {
      transform: translateY(-1px) !important;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important;
    }
    
    .menu-button.manage {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%) !important;
    }
    
    .menu-button.scrape {
      background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%) !important;
    }
    
    .menu-button.export {
      background: linear-gradient(135deg, #fa709a 0%, #fee140 100%) !important;
    }
    
    .minimized {
      width: 60px !important;
      height: 60px !important;
      min-width: 60px !important;
      max-width: 60px !important;
    }
    
    .minimized .menu-container {
      display: none !important;
    }
    
    .minimized .menu-header {
      padding: 18px !important;
      justify-content: center !important;
    }
    
    .minimized .menu-title {
      display: none !important;
    }
    
    .minimized .control-button {
      display: none !important;
    }
    
    .minimized .expand-button {
      display: block !important;
    }
    
    .expand-button {
      display: none !important;
      background: rgba(255,255,255,0.2) !important;
      border: none !important;
      color: white !important;
      width: 24px !important;
      height: 24px !important;
      border-radius: 4px !important;
      cursor: pointer !important;
      font-size: 16px !important;
    }
  `;

  document.head.appendChild(style);
  document.body.appendChild(menu);
  console.log('✅ 悬浮菜单创建完成');

  // 绑定事件
  const closeBtn = menu.querySelector('.close-button');
  const minimizeBtn = menu.querySelector('.minimize-button');
  const expandBtn = menu.querySelector('.expand-button');
  const manageBtn = menu.querySelector('.menu-button.manage');
  const scrapeBtn = menu.querySelector('.menu-button.scrape');
  const exportBtn = menu.querySelector('.menu-button.export');

  closeBtn.addEventListener('click', () => {
    console.log('❌ 关闭菜单');
    // 通知background script更新全局状态
    chrome.runtime.sendMessage({action: 'menuClosed'});
    menu.remove();
    style.remove();
  });

  minimizeBtn.addEventListener('click', () => {
    console.log('📉 缩小菜单');
    menu.querySelector('.floating-menu').classList.add('minimized');
  });

  expandBtn.addEventListener('click', () => {
    console.log('📈 展开菜单');
    menu.querySelector('.floating-menu').classList.remove('minimized');
  });

  manageBtn.addEventListener('click', () => {
    console.log('📝 打开管理页面');
    chrome.runtime.sendMessage({action: 'openManagePage'});
    menu.remove();
    style.remove();
  });

  scrapeBtn.addEventListener('click', () => {
    console.log('🕷️ 开始爬取提示词');
    scrapePrompts().then(result => {
      if (result.success) {
        console.log('✅ 爬取成功，显示成功提示');
        showToast('提示词爬取成功！', 'success');
      } else {
        console.log('❌ 爬取失败，显示错误提示:', result.error);
        showToast('爬取失败：' + result.error, 'error');
      }
    }).catch(error => {
      console.log('❌ 爬取异常，显示错误提示:', error.message);
      showToast('爬取失败：' + error.message, 'error');
    });
  });

  exportBtn.addEventListener('click', () => {
    console.log('📊 开始导出数据');
    chrome.storage.local.get(['prompts'], function(result) {
      const prompts = result.prompts || [];
      console.log('📋 当前数据量:', prompts.length);
      
      if (prompts.length === 0) {
        console.log('⚠️ 没有数据可导出');
        showToast('没有可导出的提示词数据', 'warning');
        return;
      }
      
      console.log('📝 开始生成CSV文件');
      const csvContent = createCSV(prompts);
      downloadCSV(csvContent, 'prompts.csv');
      console.log('✅ 数据导出完成');
      showToast('数据导出成功！', 'success');
    });
  });
}

// 隐藏悬浮菜单
function hideFloatingMenu() {
  // 移除当前页面的菜单
  const existingMenu = document.getElementById('prompt-manager-floating-menu');
  if (existingMenu) {
    console.log('🗑️ 移除当前页面的菜单');
    existingMenu.remove();
  }
  
  // 移除当前页面的样式
  const existingStyle = document.getElementById('prompt-manager-floating-menu-style');
  if (existingStyle) {
    existingStyle.remove();
  }
}

// 创建CSV内容
function createCSV(prompts) {
  const headers = ['image', 'prompt'];
  const rows = prompts.map(prompt => [
    prompt.image || '',
    (prompt.text || '').replace(/"/g, '""')
  ]);
  
  const csvRows = [headers, ...rows].map(row => 
    row.map(field => `"${field}"`).join(',')
  );
  
  return csvRows.join('\n');
}

// 下载CSV文件
function downloadCSV(content, filename) {
  const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', filename);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

// 显示Toast提示
function showToast(message, type = 'info') {
  const existingToast = document.querySelector('#prompt-manager-toast');
  if (existingToast) {
    existingToast.remove();
  }

  const toast = document.createElement('div');
  toast.id = 'prompt-manager-toast';
  toast.textContent = message;
  
  let backgroundColor = '#2196f3';
  if (type === 'success') {
    backgroundColor = '#4caf50';
  } else if (type === 'error') {
    backgroundColor = '#f44336';
  } else if (type === 'warning') {
    backgroundColor = '#ff9800';
  }
  
  toast.style.cssText = `
    position: fixed;
    top: 20px;
    left: 50%;
    transform: translateX(-50%);
    background: ${backgroundColor};
    color: white;
    padding: 12px 24px;
    border-radius: 6px;
    z-index: 10001;
    font-size: 14px;
    font-weight: 500;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    opacity: 0;
    transition: opacity 0.3s ease-in-out;
  `;
  
  document.body.appendChild(toast);
  
  setTimeout(() => {
    toast.style.opacity = '1';
  }, 10);
  
  setTimeout(() => {
    toast.style.opacity = '0';
    setTimeout(() => {
      if (toast.parentNode) {
        toast.parentNode.removeChild(toast);
      }
    }, 300);
  }, 2000);
}

// 从URL生成缩略图
async function generateThumbnailFromUrl(imageUrl, maxWidth = 300, maxHeight = 300, quality = 0.7) {
  console.log(`🖼️ 开始从URL生成缩略图: ${imageUrl}`);
  
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'anonymous'; // 允许跨域
    
    img.onload = () => {
      try {
        console.log(`📐 原图尺寸: ${img.width}x${img.height}`);
        
        // 计算缩略图尺寸，保持宽高比
        let { width, height } = calculateThumbnailSize(img.width, img.height, maxWidth, maxHeight);
        console.log(`📏 缩略图尺寸: ${width}x${height}`);
        
        // 创建canvas
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = width;
        canvas.height = height;
        
        // 绘制缩略图
        ctx.drawImage(img, 0, 0, width, height);
        
        // 转换为base64，使用JPEG格式以减小文件大小
        const thumbnailDataUrl = canvas.toDataURL('image/jpeg', quality);
        console.log(`✅ 缩略图生成完成，数据长度: ${thumbnailDataUrl.length}`);
        
        resolve(thumbnailDataUrl);
      } catch (error) {
        console.error('❌ 生成缩略图失败:', error);
        // 如果生成缩略图失败，返回原图URL
        resolve(imageUrl);
      }
    };
    
    img.onerror = (error) => {
      console.error('❌ 图片加载失败:', error);
      // 如果图片加载失败，返回原图URL
      resolve(imageUrl);
    };
    
    img.src = imageUrl;
  });
}

// 计算缩略图尺寸，保持宽高比
function calculateThumbnailSize(originalWidth, originalHeight, maxWidth, maxHeight) {
  let width = originalWidth;
  let height = originalHeight;
  
  // 如果原图尺寸小于最大尺寸，直接返回原尺寸
  if (width <= maxWidth && height <= maxHeight) {
    return { width, height };
  }
  
  // 计算缩放比例
  const widthRatio = maxWidth / width;
  const heightRatio = maxHeight / height;
  const ratio = Math.min(widthRatio, heightRatio);
  
  width = Math.floor(width * ratio);
  height = Math.floor(height * ratio);
  
  return { width, height };
}

// 爬取提示词功能
async function scrapePrompts() {
  console.log('🚀 开始爬取提示词...');
  
  try {
    // 查找图片元素
    console.log('🔍 查找图片元素...');
    const imageElement = document.querySelector('.EdgeImage_image__iH4_q.max-h-full.w-auto.max-w-full');
    if (!imageElement) {
      console.error('❌ 未找到图片元素，选择器: .EdgeImage_image__iH4_q.max-h-full.w-auto.max-w-full');
      throw new Error('未找到图片元素');
    }
    
    const imageSrc = imageElement.src;
    if (!imageSrc) {
      console.error('❌ 图片地址为空');
      throw new Error('图片地址为空');
    }
    console.log('✅ 找到图片:', imageSrc);

    // 查找提示词元素
    console.log('🔍 查找主要提示词元素...');
    let promptElement = document.querySelector('.mantine-focus-auto.relative.break-words.text-sm.m_b6d8b162.mantine-Text-root');
    let promptText = '';
    
    if (promptElement) {
      promptText = promptElement.textContent || promptElement.innerText;
      console.log('✅ 找到主要提示词元素，内容:', promptText);
    } else {
      console.log('⚠️ 未找到主要提示词元素，选择器: .mantine-focus-auto.relative.break-words.text-sm.m_b6d8b162.mantine-Text-root');
    }
    
    // 如果提示词为空，尝试从span标签中获取
    if (!promptText || promptText.trim() === '') {
      console.log('🔍 主要提示词为空，开始查找span标签结构...');
      
      // 查找所有span标签
      const allSpans = document.querySelectorAll('span');
      console.log('📋 找到所有span标签数量:', allSpans.length);
      
      let tagSpan = null;
      for (let i = 0; i < allSpans.length; i++) {
        const span = allSpans[i];
        console.log(`🔍 检查span[${i}]:`, span.textContent);
        if (span.textContent === 'Tag') {
          tagSpan = span;
          console.log('✅ 找到Tag span标签:', span);
          break;
        }
      }
      
      if (tagSpan) {
        console.log('🔍 开始从Tag span获取标签数据...');
        
        // 获取span的parent()的下一个同级元素div
        let currentElement = tagSpan;
        console.log('📍 当前元素:', currentElement);
        
        for (let i = 0; i < 1; i++) {
          currentElement = currentElement.parentElement;
          console.log(`📍 向上查找父级[${i+1}]:`, currentElement);
          if (!currentElement) {
            console.log('❌ 无法找到足够的父级元素');
            break;
          }
        }
        
        if (currentElement) {
          console.log('✅ 找到目标父级元素:', currentElement);
          let nextDiv = currentElement.nextElementSibling;
          const tagTexts = [];
          let divCount = 0;
          
          console.log('🔍 开始遍历同级div元素...');
          
          // 遍历所有下一个同级元素div，直到没有下一个
          while (nextDiv && nextDiv.tagName === 'DIV') {
            divCount++;
            console.log(`📍 找到第${divCount}个同级div:`, nextDiv);
            
            // 获取这个div下的所有a元素（包括子孙元素）
            const aElements = nextDiv.querySelectorAll('a');
            console.log(`🔍 在div[${divCount}]中找到${aElements.length}个a元素`);
            
            aElements.forEach((a, index) => {
              const text = a.textContent || a.innerText;
              console.log(`  📝 a元素[${index}]:`, text);
              if (text && text.trim()) {
                tagTexts.push(text.trim());
                console.log(`  ✅ 添加标签:`, text.trim());
              }
            });
            
            nextDiv = nextDiv.nextElementSibling;
          }
          
          console.log('📊 标签收集结果:', tagTexts);
          
          if (tagTexts.length > 0) {
            promptText = tagTexts.join(', ');
            console.log('✅ 成功从span标签结构获取提示词:', promptText);
          } else {
            console.log('⚠️ 未从span标签结构中找到任何标签');
          }
        } else {
          console.log('❌ 无法找到目标父级元素');
        }
      } else {
        console.log('❌ 未找到包含"Tag"文本的span标签');
      }
    }
    
    if (!promptText || promptText.trim() === '') {
      console.error('❌ 最终提示词内容为空');
      throw new Error('提示词内容为空');
    }
    
    console.log('✅ 最终获取到的提示词:', promptText);

    // 获取现有数据
    console.log('🔍 检查现有数据...');
    const result = await chrome.storage.local.get(['prompts']);
    const existingPrompts = result.prompts || [];
    console.log('📊 现有提示词数量:', existingPrompts.length);
    
    // 检查是否已存在相同的提示词或图片
    const trimmedText = promptText.trim();
    console.log('🔍 检查重复数据...');
    console.log('📝 当前提示词:', trimmedText);
    console.log('🖼️ 当前图片:', imageSrc);
    
    const isDuplicate = existingPrompts.some((prompt, index) => {
      // 检查提示词文本是否相同（忽略大小写和多余空格）
      const textMatch = prompt.text.toLowerCase().replace(/\s+/g, ' ') === trimmedText.toLowerCase().replace(/\s+/g, ' ');
      // 检查图片地址是否相同
      const imageMatch = prompt.image === imageSrc;
      
      if (textMatch || imageMatch) {
        console.log(`⚠️ 发现重复数据[${index}]:`, {
          textMatch,
          imageMatch,
          existingText: prompt.text,
          existingImage: prompt.image
        });
      }
      
      return textMatch || imageMatch;
    });
    
    if (isDuplicate) {
      console.error('❌ 检测到重复数据，拒绝添加');
      throw new Error('该提示词或图片已存在，请勿重复添加');
    }

    // 添加新提示词
    console.log('✅ 数据验证通过，准备添加新提示词...');
    
    // 生成缩略图
    console.log('🖼️ 开始为爬取的图片生成缩略图...');
    const thumbnailDataUrl = await generateThumbnailFromUrl(imageSrc);
    console.log('📸 缩略图生成完成，数据长度:', thumbnailDataUrl.length);
    
    const newPrompt = {
      id: Date.now(),
      text: promptText.trim(),
      image: thumbnailDataUrl, // 使用缩略图
      originalImage: imageSrc, // 保存原图URL
      timestamp: new Date().toISOString(),
      lastUpdated: new Date().toISOString(),
      source: 'scrape',
      isFavorite: false
    };
    
    console.log('📝 新提示词数据:', newPrompt);
    
    existingPrompts.push(newPrompt);
    
    // 保存到存储
    console.log('💾 保存数据到本地存储...');
    await chrome.storage.local.set({prompts: existingPrompts});
    console.log('✅ 数据保存成功，总数:', existingPrompts.length);
    
    // 提交到服务器
    console.log('🌐 提交数据到服务器...');
    try {
      const serverData = {
        chrome_id: newPrompt.id.toString(),
        text: newPrompt.text,
        image_data: newPrompt.image,
        original_image: newPrompt.originalImage,
        source: newPrompt.source,
        is_favorite: newPrompt.isFavorite
      };
      
      const response = await fetch(`${CONFIG.getApiBaseUrl()}/prompts`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(serverData)
      });
      
      if (response.ok) {
        console.log('✅ 数据已成功提交到服务器');
      } else {
        console.log('⚠️ 服务器提交失败，但本地保存成功');
      }
    } catch (error) {
      console.log('⚠️ 服务器提交失败，但本地保存成功:', error.message);
    }
    
    return {
      success: true,
      message: '提示词爬取成功',
      data: newPrompt
    };
    
  } catch (error) {
    console.error('❌ 爬取失败:', error.message);
    console.error('❌ 错误堆栈:', error.stack);
    return {
      success: false,
      error: error.message
    };
  }
}
